package com.yzz.shopping.ui.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.widget.ViewPager2
import com.yzz.shopping.R
import com.yzz.shopping.entity.GlideRecommendBean
import com.yzz.shopping.ui.viewholder.ShoppingViewHolder
import kotlin.math.abs

/**
 * @Author : yangzuozhe
 * @Time : On 2022/3/31 9:28
 *
 * @Description : ShoppingBannerAdapter
 */
class ShoppingBannerAdapter(
    val mActivty: FragmentActivity,
    val mList: MutableList<GlideRecommendBean?>
) : ShoppingAdapter(mActivty, mList, true) {

    var nowPage = getStartPosition()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ShoppingViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_shopping_search, parent, false)
        view.layoutParams.apply {
            //viewpager2 宽高得等于 match
            height = ViewGroup.LayoutParams.MATCH_PARENT
        }
        return ShoppingViewHolder(view)
    }

    override fun onBindViewHolder(holder: ShoppingViewHolder, position: Int) {
        super.onBindViewHolder(holder, getReleasePosition(position))
    }

    fun getReleasePosition(position: Int): Int {
        val index = position - getStartPosition()
        val holderPosition: Int
        if (index % mList.size == 0) {
            holderPosition = 0
        } else if (index > 0) {
            if (index < mList.size) {
                holderPosition = index
            } else {
                val newIndex = index % mList.size
                holderPosition = newIndex
            }
        } else if (index < 0) {
            if (abs(index) <= mList.size) {
                val deIndex = index + mList.size
                holderPosition = deIndex
            } else {
                val newIndex = index % mList.size
                val finalIndex = newIndex + mList.size
                holderPosition = finalIndex
            }
        } else {
            holderPosition = 0
        }
        return holderPosition
    }

    fun pageNext(viewpager2: ViewPager2) {
        viewpager2.currentItem = ++nowPage
    }

    fun pagePrevious(viewpager2: ViewPager2) {
        viewpager2.currentItem = --nowPage
    }

    fun getStartPosition(): Int = Int.MAX_VALUE / 2

    override fun getItemCount(): Int {
        return Int.MAX_VALUE
    }

}